package com.example.hissys.controller;

import com.example.hissys.entity.User;
import com.example.hissys.service.UserService;
import com.example.hissys.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")  // 允许所有来源，也可以指定具体域名
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    // 用户注册
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        try {
            userService.register(user);
            return "注册成功";
        } catch (RuntimeException e) {
            return "注册失败：" + e.getMessage();
        }
    }

    // 用户登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        try {
            User loggedInUser = userService.login(user.getUsername(), user.getPassword());
            String token = jwtUtil.generateToken(loggedInUser.getUsername());
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("message", "登录成功");
            return response;
        } catch (RuntimeException e) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录失败：" + e.getMessage());
            return response;
        }
    }

    /**
     * 根据用户名查询用户ID
     * @param username 用户名
     * @return 用户ID
     */
    @GetMapping("/id")
    public ResponseEntity<?> getUserIdByUsername(@RequestParam String username) {
        try {
            Integer userId = userService.getUserIdByUsername(username);
            if (userId != null) {
                return ResponseEntity.ok(userId);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("查询用户ID失败：" + e.getMessage());
        }
    }
}

